package com.xqls.server.dto;

import com.alibaba.fastjson.JSONObject;
import com.xqls.bean.OperationRecordBean;
import com.xqls.biz.SokectBiz;
import com.xqls.server.dto.recive.WastegasDto;
import com.xqls.server.netty.DecoderUtil;
import com.xqls.util.ContextUtil;
import io.netty.buffer.ByteBuf;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hdg on 2017/7/11.
 */
public class FluSoketCommonDto implements Serializable {
    private static Logger logger = Logger.getLogger(FluSoketCommonDto.class);
    private static final String HEAD_STR = "##";//针头

    private static final String END_STR = "\r\n";//针尾

    private List<WastegasDto> datas=new ArrayList<>();

    private Map<String,Object> simpleMap=new HashMap<>();
    private  String  reciveStr;

    public String getReciveStr() {
        return reciveStr;
    }

    public void setReciveStr(String reciveStr) {
        this.reciveStr = reciveStr;
    }

    public Map<String, Object> getSimpleMap() {
        return simpleMap;
    }

    public void setSimpleMap(Map<String, Object> simpleMap) {
        this.simpleMap = simpleMap;
    }

    private  String deviceName;
    /**
     * 帧头
     */
    private String head= "##";

    private  String ST;  //系统编号
    private  String CN;  //命令编号
    private  String PW;  //访问密码
    private String data;    //数据内容
    private  String check;  //检验

    /**
     * 设备地址
     */
    private String adress;

    /**
     * 帧尾
     */
    private String end="CRLF";

    private OperationRecordBean activeOperationRecordBean;

    public OperationRecordBean getActiveOperationRecordBean() {
        return activeOperationRecordBean;
    }

    public void setActiveOperationRecordBean(OperationRecordBean activeOperationRecordBean) {
        this.activeOperationRecordBean = activeOperationRecordBean;
    }

    public String getDeviceName() {
        return deviceName;
    }

    public void setDeviceName(String deviceName) {
        this.deviceName = deviceName;
    }

    public String getAdress() {
        return adress;
    }

    public void setAdress(String adress) {
        this.adress = adress;
    }

    public String getHead() {
        return head;
    }

    public void setHead(String head) {
        this.head = head;
    }

    public String getEnd() {
        return end;
    }

    public void setEnd(String end) {
        this.end = end;
    }

    public String getST() {
        return ST;
    }

    public void setST(String ST) {
        this.ST = ST;
    }

    public String getCN() {
        return CN;
    }

    public void setCN(String CN) {
        this.CN = CN;
    }

    public String getPW() {
        return PW;
    }

    public void setPW(String PW) {
        this.PW = PW;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public String getCheck() {
        return check;
    }

    public void setCheck(String check) {
        this.check = check;
    }

    public static FluSoketCommonDto getDecode(ByteBuf in) {
        if (in.readableBytes() <= 0)
            return null;
        String reciveStr=DecoderUtil.byteToAscii(in,in.readableBytes());
        if(StringUtils.isEmpty(reciveStr)){
            return null;
        }
        String head = reciveStr.substring(0,2);
        if (!HEAD_STR.equals(head)) {
            return null;
        }
        try {
            FluSoketCommonDto dto =new FluSoketCommonDto();
            dto.setHead(head);
            dto.setST(getSubString(reciveStr,"ST=",";"));
            dto.setCN(getSubString(reciveStr,"CN=",";"));
            dto.setPW(getSubString(reciveStr,"PW=",";"));
            dto.setData(getSubString(reciveStr,"CP=&&","&&"));
            dto.setCheck(reciveStr.substring(reciveStr.length()-6).substring(0,4));
            dto.setAdress(getSubString(reciveStr,"MN=",";"));
            String dataStr=dto.getData();
            Map<String,Object> simpleMap=new HashMap<>();
            List<WastegasDto> datas=new ArrayList<>();
            if(StringUtils.isNotEmpty(dataStr)){
                String[]  data=dataStr.split(";");
                String[]  realdata;
                String[]  wastegasData;
                WastegasDto tmp;
                String tmpKey;
                 for(String singleData:data){
                     if(singleData.indexOf(",")>=0){
                         wastegasData=singleData.split(",");
                         tmp=new WastegasDto();
                         for (String wastSingleData:wastegasData){
                             realdata=wastSingleData.split("=");
                             tmpKey=realdata[0];
                           tmp.setCode(tmpKey.split("-")[0]);
                             if(tmpKey.indexOf("Rtd")>=0){
                                 tmp.setRtd(realdata[1]);
                             }else if(tmpKey.indexOf("Flag")>=0){
                                 tmp.setFlag(realdata[1]);
                             }
                         }
                         datas.add(tmp);
                     }else{
                         realdata=singleData.split("=");
                                 simpleMap.put(realdata[0],realdata[1]);
                     }
                 }
                dto.setDatas(datas);
                dto.setSimpleMap(simpleMap);
            }
            String end = reciveStr.substring(reciveStr.length()-2);
            if (!END_STR.equals(end)) {
                throw new RuntimeException("结束的字节不正确");
            }
            dto.setEnd(end);
            return dto;
        } catch (Exception e) {
            logger.error("解码客户端信息异常", e);
        }
        return null;
    }




    public List<WastegasDto> getDatas() {
        return datas;
    }

    public void setDatas(List<WastegasDto> datas) {
        this.datas = datas;
    }

    public void encode(ByteBuf byteBuf) {
        byteBuf.writeBytes(DecoderUtil.hexStringToBytes(end));
    }

    public void operate() {
        SokectBiz sokectBiz=(SokectBiz) ContextUtil.getBean(SokectBiz.class);
        sokectBiz.wastegasRecive(this);
    }

    private static String  getSubString(String str,String strartStr,String endStr){
        String tmp=str.substring(str.indexOf(strartStr)+strartStr.length());
              tmp=tmp.substring(0,tmp.indexOf(endStr));
        return tmp;
    }



    public String  toString (){
        return JSONObject.toJSONString(this);
    }
}
